/**
 * 图表loading配置
 */
export const loadingOptions = {
  text: '加载中...',
  color: '#4ea397',
  maskColor: 'rgba(255, 255, 255, 0.4)'
}

/**
 * 图表名称转换
 * @param {String} type
 * @returns Object
 */
function echartDataMap(type) {
  const obj = {
    legend: '',
    name: ''
  }
  if (type === 'apdex') {
    obj.legend = ['服务满意度']
    obj.name = '服务满意度'
  } else if (type === 'callTimes') {
    obj.legend = ['吞吐率']
    obj.name = '吞吐率'
  } else if (type === 'errorCount') {
    obj.legend = ['服务错误数']
    obj.name = '服务错误数'
  } else if (type === 'errorRate') {
    obj.legend = ['错误率']
    obj.name = '错误率'
  } else if (type === 'avgCostTime') { //  响应时间曲线图
    obj.legend = ['响应时间曲线图']
    obj.name = '响应时间曲线图'
  } else if (type === 'respTime') { // 服务器响应时间
    obj.legend = ['外部调用', '数据库', '缓存', '总计']
    obj.name = '应用服务器响应时间'
  } else if (type === 'respTimeTantile') { // 服务器响应时间分位图
    obj.legend = ['50%分位值', '75%分位值', '95%分位值', '99%分位值']
    obj.name = '应用服务器响应时间分位值'
  } else if (type === 'transTimeConsum') { // Top5耗时事物
    obj.legend = []
    obj.name = 'Top5耗时事物'
  } else if (type === 'respTimeThroughput') { // 响应时间和吞吐率
    obj.legend = ['平均响应时间', '吞吐率']
    obj.name = '响应时间和吞吐率'
  } else if (type === 'performDecomStack') { // 事务性能分解堆叠图
    obj.legend = []
    obj.name = '事务性能分解堆叠图'
  } else if (type === 'timeOccupyRate') { // 事务在整个链路中占用时间比
    obj.legend = ['事务在整个链路中占用时间比']
    obj.name = '事务在整个链路中占用时间比'
  } else if (type === 'traceList') { // 慢事务追踪
    obj.legend = ['慢事务追踪']
    obj.name = '慢事务追踪'
  }
  return obj
}

// 颜色值配置，超过数量后循环使用
const color = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']

/**
 * echart 折线图数据格式转换
 * 多条折线转换方法
 * @param { Object, String }
 * @returns Object
 */
export function multiLineTrans(datas, type, options) {
  if (!datas || typeof datas !== 'object') return

  // 默认颜色
  let curColor = color

  const dataValueObj = { // 初始化数据结构
    xData: [],
    yData: []
  }
  const resData = datas // 获取的数据类型，对象
  const tooltip = {
    trigger: 'axis'
  }
  let xAxis = {
    type: 'category',
    data: dataValueObj.xData,
    boundaryGap: false
  }
  let yAxis = {
    type: 'value'
  }
  const seriesDatas = []
  const dynamicLegend = []

  if (type === 'pod') {
    const yunit = options.yunit

    if (options.color !== undefined) {
      curColor = options.color
    }

    const dataKeyArray = {}
    dataKeyArray[options.yItem] = {}

    dataValueObj.yData = {}

    Object.keys(resData).forEach((key, index) => {
      dynamicLegend.push(key) // 动态legend

      dataValueObj.yData[index] = {}
      Object.keys(dataKeyArray).forEach(dataKey => {
        dataValueObj.yData[index][dataKey] = []
      })

      resData[key].forEach(item => { // item 具体对象属性
        if (index === 0) {
          dataValueObj.xData.push(item[options.xItem])
        }

        Object.keys(dataKeyArray).forEach(dataKey => {
          dataValueObj.yData[index][dataKey].push(item[dataKey])
        })
      })

      const ydataOjb = dataValueObj.yData[index][options.yItem]
      const data = {
        name: key,
        type: options.type,
        data: ydataOjb
      }
      if (options.area) {
        data['areaStyle'] = {}
      }
      seriesDatas.push(data)
    })
    const yAxisVal = {
      type: 'category',
      inverse: options.inverse === undefined ? true : options.inverse,
      data: dataValueObj.xData
    }
    const xAxisVal = [
      {
        type: 'value',
        name: `${options.yUnitLabel}(${yunit})`,
        min: 0
      }
    ]

    yAxis = options.reverse ? xAxisVal : yAxisVal
    xAxis = options.reverse ? yAxisVal : xAxisVal

    xAxis['boundaryGap'] = false
  }

  return {
    tooltip: tooltip,
    legend: {
      left: 'center',
      data: dynamicLegend.length ? dynamicLegend : echartDataMap(type).legend,
      bottom: 5,
      type: 'scroll'
    },
    toolbox: {
      feature: {
        saveAsImage: {
          name: echartDataMap(type).name
        },
        dataZoom: {},
        restore: {}
      }
    },
    color: curColor,
    xAxis: xAxis,
    yAxis: yAxis,
    series: seriesDatas
  }
}

export function sortData(data) {
  // 数据排序，防止图形绘制被覆盖
  const keys = Object.keys(data)
  const getKeyByWord = (word, keys) => {
    const len = keys.length
    for (let i = 0; i < len; i++) {
      const originKey = keys[i]
      const key = originKey.toLowerCase()
      if (key.indexOf(word) !== -1) {
        return originKey
      }
    }
    return ''
  }

  const usedKey = getKeyByWord('use', keys)
  const limitKey = getKeyByWord('limit', keys)

  if (usedKey !== '' && limitKey !== '') {
    const sortObj = {}
    sortObj[limitKey] = data[limitKey]
    sortObj[usedKey] = data[usedKey]
    return sortObj
  }

  return data
}

export function makeEchart(res, area) {
  // 显示单位
  const opts = {
    // 颜色
    color: ['#91cc75', '#ff6666'],
    // y轴坐标单位
    yunit: res.meta.unit,
    // y轴显示字段
    yItem: res.meta.yItem,
    // x轴显示字段
    xItem: res.meta.xItem,
    // y轴标题
    yUnitLabel: '',
    // 图形形状
    type: 'line',
    // 翻转
    reverse: true,
    inverse: false,
    // 面积堆叠图
    area: (area === undefined ? true : area)
  }
  const showData = sortData(res.content)
  return multiLineTrans(showData, 'pod', opts)
}
